import sys
from socket import *
import signal
import pycoev

def sighandler(signum, frame):
    # should do a soft shutdown
    # deleting the fd and
    # deinitializing the library
    pycoev.deinit()
    sys.exit(0)
    

def rw_callback(evloop=None, events=None, csocket=None):
    if events & pycoev.TIMEOUT:
        # was: close_conn(evloop, csocket)
        # now it does all here
        print("closing %s" % (str(csocket)))
        evloop.delete(csocket)
        csocket.close()

    data = csocket.recv(1024)
    print(data)
    csocket.send(data)
    
def accept_cb(evloop=None, events=None, ssocket=None):
    csocket, caddr = ssocket.accept()
    print("csocket: %s" % (str(csocket)))
    csocket.setblocking(0)
    evloop.add(fd=csocket, events=pycoev.READ, timeout=10, callback=rw_callback, cb_arg=csocket)
    

def server():
    ssocket = socket(AF_INET, SOCK_STREAM)
    ssocket.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
    ssocket.bind(("127.0.0.1", 8080))
    print("starting on: %s" % (gethostname()))
    ssocket.listen(5)
    ssocket.setblocking(0)
    signal.signal(signal.SIGINT, sighandler)
    
    pycoev.init(100)
    evloop = pycoev.Loop(60)

    evloop.add(fd=ssocket, events=pycoev.READ, timeout=0, callback=accept_cb, cb_arg=ssocket)
    print("ssocket: %s" % (str(ssocket)))
    
    while 1:
        evloop.loop_once(10)
    
if __name__ == "__main__": 
    server()